import Vue from 'vue'
Vue.prototype.$getDate = getDate; //传时间戳  时间戳转化为格式  1970-01-23 
Vue.prototype.$regTest = regTest; //字符判断
Vue.prototype.plusXing = plusXing; //数字中间显示***   1333******222
Vue.prototype.$toast = toast; //消息提示
Vue.prototype.$navBack = navBack; //返回上一步
Vue.prototype.$redirectTo = redirectTo; //重新打开
Vue.prototype.$navTo = navTo; //普通跳转
Vue.prototype.$tabTo = tabTo; //tab跳转
Vue.prototype.$scanQrCode = scanQrCode; //扫码
Vue.prototype.$copy = copy; //复制
Vue.prototype.$accMul = accMul; //加法
Vue.prototype.$sub = sub; //减法
Vue.prototype.$mul = mul; //乘法
Vue.prototype.$floatDiv = floatDiv; //除法
Vue.prototype.floatNum = floatNum; //小数点后几个0
Vue.prototype.$saveHeadImgFile = saveHeadImgFile; //单一图片保存
Vue.prototype.$formatDecimal = formatDecimal; //保留几位小数,不四舍五入
Vue.prototype.$previewImage = previewImage; //保留几位小数,不四舍五入
// FilterNullToEmpty - null转空字符串
// FilterAmountFormat  - 金额格式化显示
// FilterMoneyFormat - 数字格式化显示
// FilterTextMaxLength - 字符串过长截断
// FilterWanFormat - 数字格式化显示,单位为万
// FilterIdCard - 身份证隐藏
function previewImage(urls = [], current = 0) {
	uni.previewImage({
		urls: urls,
		current: current,
		indicator: 'default',
		loop: true,
		fail(err) {
			console.log('previewImage出错', urls, err)
		},
	})
}

function formatDecimal(num, decimal) {
	num = num.toString()
	let index = num.indexOf('.')
	if (index !== -1) {
		num = num.substring(0, decimal + index + 1)
	} else {
		num = num.substring(0)
	}
	return parseFloat(num).toFixed(decimal)
}

function plusXing(str, frontLen, endLen) {
	var xing = "****";
	return str.substr(0, frontLen) + xing + str.substr(str.length - endLen);
}

function getnum(num) {
	return Math.floor(num * 10000) / 10000;
}
/**
 * 用户扫码
 * 不支持h5
 * 异步方法
 * */
function scanQrCode() {
	// 允许从相机和相册扫码
	return new Promise((reslove, recject) => {
		// #ifdef APP-PLUS
		uni.scanCode({
			success: (res) => {
				reslove(res);
			},
			fail: (err) => {
				recject(err);
			}
		});
		// #endif
		// #ifdef H5
		uni.showToast({
			title: 'H5不支持扫码',
			duration: 1000,
			icon: 'none'
		})
		// #endif
	})
}
//复制
function copy(txt) {
	let _this = this;
	uni.setClipboardData({
		data: txt.toString(),
		success: function() {
			uni.showToast({
				icon: 'none',
				title: '复制成功'
			});
		}
	});
	// // #ifdef H5
	// uni.showToast({
	// 	icon: 'none',
	// 	title: 'H5暂不支持复制！'
	// });
	// // #endif
}

function navBack(d) {
	uni.navigateBack({
		delta: d || 1
	})
}

function saveHeadImgFile(base64, quality = 100) {
	// #ifdef H5
	uni.showToast({
		icon: 'none',
		title: '长按图片保存！'
	});
	// #endif
	// #ifdef APP-PLUS
	const bitmap = new plus.nativeObj.Bitmap('test');
	return new Promise((resolve, reject) => {
		// 从本地加载Bitmap图片
		bitmap.loadBase64Data(base64, function() {
			const url = '_doc/' + new Date().getTime() + '.png'; // url为时间戳命名方式
			bitmap.save(url, {
				overwrite: true, // 是否覆盖
				quality: quality // 图片清晰度
			}, i => {
				console.log(url);
				uni.saveImageToPhotosAlbum({
					filePath: url,
					success: function() {
						plus.nativeUI.toast('保存成功', {
							align: 'center',
							verticalAlign: 'center'
						});
					}
				});
			}, e => {
				plus.nativeUI.toast('保存图片失败', {
					align: 'center',
					verticalAlign: 'center'
				});
			});
		}, e => {
			plus.nativeUI.toast('加载图片失败', {
				align: 'center',
				verticalAlign: 'center'
			});
		});
	});
	// #endif
}

function toast(config, duration = 1400) {
	if (typeof config === 'string') {
		// #ifdef APP-PLUS
		plus.nativeUI.toast(config, {
			duration: duration,
			align: "center",
			verticalAlign: "center",
		})
		// #endif
		// #ifdef H5
		uni.showToast({
			title: config,
			duration: duration,
			icon: 'none'
		})
		// #endif
	} else {
		uni.showToast(config)
	}
}

function redirectTo(url) {
	uni.redirectTo({
		url: url
	})
}

function navTo(url) {
	uni.navigateTo({
		url: url
	})
}

function tabTo(url) {
	uni.switchTab({
		url: url
	})
}

function regTest(type, value) {
	if (type == 'phone') {
		if (value.length == 0) {
			toast('请输入手机号');
			return false;
		}
		if (/^[0-9]\d*$/.test(value)) {
			return true
		} else {
			toast('手机号不合法');
			return false;
		}
	}
	if (type == 'email') {
		if (value.length == 0) {
			toast(this.lang.entPhone);
			return;
		}
		if (/^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/.test(value)) {
			return true
		} else {
			toast('邮箱不合法');
			return false;
		}
	}
	return true;
}

function getDate(timestamp) {
	if ((timestamp + '').length == 10) {
		timestamp *= 1000;
	}
	// if(timestamp==''){timestamp=new Date().getTime()}
	var date = new Date(timestamp); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
	var Y = date.getFullYear() + '-';
	var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
	var D = date.getDate() + ' ';
	var h = date.getHours() + ':';
	var m = date.getMinutes() + ':';
	var s = date.getSeconds();
	return Y + M + D;
}
// 加法
function accMul(a, b) {
	if (a == null) {
		return;
	}
	if (b == null) {
		return;
	}
	var c, d, e;
	try {
		c = a.toString().split(".")[1].length;
	} catch (f) {
		c = 0;
	}
	try {
		d = b.toString().split(".")[1].length;
	} catch (f) {
		d = 0;
	}
	return e = Math.pow(10, Math.max(c, d)),
		(mul(a, e) + mul(b, e)) / e;
}
// 减法
function sub(a, b) {
	if (a == null) {
		return;
	}
	if (b == null) {
		return;
	}
	var c, d, e;
	try {
		c = a.toString().split(".")[1].length;
	} catch (f) {
		c = 0;
	}
	try {
		d = b.toString().split(".")[1].length;
	} catch (f) {
		d = 0;
	}
	return e = Math.pow(10, Math.max(c, d)),
		(mul(a, e) - mul(b, e)) / e;
}
//乘法
function mul(a, b) {
	if (a == null) {
		return;
	}
	if (b == null) {
		return;
	}
	var c = 0,
		d = a.toString(),
		e = b.toString();
	try {
		c += d.split(".")[1].length;
	} catch (f) {}
	try {
		c += e.split(".")[1].length;
	} catch (f) {}
	return (
		(Number(d.replace(".", "")) * Number(e.replace(".", ""))) / Math.pow(10, c));
}
//除法
function floatDiv(arg1, arg2) {
	if (arg1 == null) {
		return;
	}
	if (arg2 == null) {
		return;
	}
	var t1 = 0,
		t2 = 0,
		r1,
		r2;
	try {
		t1 = arg1.toString().split(".")[1].length;
	} catch (e) {}
	try {
		t2 = arg2.toString().split(".")[1].length;
	} catch (e) {}
	r1 = Number(arg1.toString().replace(".", ""));
	r2 = Number(arg2.toString().replace(".", ""));
	return (r1 / r2) * Math.pow(10, t2 - t1);
	// return (r1 / r2);
}

function floatNum(val) {
	let str = val.toString();
	if (val == 0 || val == "") {
		return "";
	} else {
		if (str.indexOf(".") != -1) {
			if (str.split(".")[1].length == 1) {
				return val + "000";
			} else if (str.split(".")[1].length == 2) {
				return val + "00";
			} else if (str.split(".")[1].length == 3) {
				return val + "0";
			} else if (str.split(".")[1].length == 4) {
				return val;
			} else if (str.split(".")[1].length > 4) {
				return str.split(".")[0] + "." + str.split(".")[1].substring(0, 4);
			}
		} else {
			return val + ".0000";
		}
	}
}
Vue.filter('numFixed', function(v, n = 2) {
	if (parseFloat(v).toString() == "NaN") {
		return v
	}
	var r = (v - 0).toFixed(n);
	return r == 0 ? 0.00 : r
})
Vue.filter('numSlice', function(v, n = 2) {
	// return (v-0).toFixed(n)
	v += '';
	var i = v.indexOf('.');
	if (i == -1) {
		return (v - 0).toFixed(n)
	} else {
		return v.slice(0, i + n + 1);
	}
})
Vue.filter('timeToDate', function(timestamp) {
	if ((timestamp + '').length == 10) {
		timestamp *= 1000;
	}
	// if(timestamp==''){timestamp=new Date().getTime()}
	var date = new Date(timestamp); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
	var Y = date.getFullYear() + '-';
	var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
	var D = date.getDate() + ' ';
	var h = date.getHours() + ':';
	var m = date.getMinutes() + ':';
	var s = date.getSeconds();
	return Y + M + D;
}, )
// 时间戳转日期(1569736900 => 2019-09-29)
Vue.filter('timeFilter', function(str, type) {
	if (!str) {
		return '- -'
	}
	str = String(str).length <= 10 ? str * 1000 : str;
	let formatTime = (a) => parseInt(a) < 10 ? '0' + parseInt(a) : parseInt(a);
	let t = new Date(str);
	let year = t.getFullYear();
	let month = formatTime(t.getMonth() + 1);
	let day = formatTime(t.getDate());
	let hours = formatTime(t.getHours());
	let minutes = formatTime(t.getMinutes());
	let seconds = formatTime(t.getSeconds());
	let text = ``;
	// 判断当前时间段
	if (hours >= 0 && hours <= 10) {
		text = `早上`;
	} else if (hours > 10 && hours <= 14) {
		text = `中午`;
	} else if (hours > 14 && hours <= 18) {
		text = `下午`;
	} else if (hours > 18 && hours <= 24) {
		text = `晚上`;
	}
	if (type == "ymd") {
		return `${year}-${month}-${day}`;
	} else if (type == 'hms') {
		return `${hours}:${minutes}:${seconds}`;
	} else if (type == 'hm') {
		return `${text} ${hours}:${minutes}`;
	} else if (type == 'ms') {
		return `${minutes}:${seconds}`;
	} else if (type == 'ymdhm') {
		return `${year}-${month}-${day} ${hours}:${minutes}`;
	} else if (type == "article") {
		//6月13号 13:00
		return `${month}月${day}日 ${hours}:${minutes}`
	} else if (type == "order") {
		//6月13号 13:00
		return `${year}年${month}月${day}日`
	} else {
		return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
	}
})
/*日期转换*/
Vue.filter('dateFilter', function(str) {
	return str.slice(0, 4) + '-' + str.slice(4, 6) + '-' + str.slice(6);
});
// 手机号隐藏('13912345678' => '139****5678'),此处str必须为字符串
Vue.filter('telHide', function(str) {
	return str.replace(/(\d{3})\d{4}(\d*)/, '$1****$2')
});
// 隐藏姓名(小明=>*明    李小明=>李*明)
Vue.filter('nameHide', function(name) {
	if (name.length === 2) {
		return new Array(name.length).join('*') + name.substr(-1)
	} else {
		return (name.substr(0, 1) + new Array(name.length - 1).join('*') + name.substr(-1))
	}
});
// 身份证号隐藏('331082199708094687' => '33108219********87')
Vue.filter('IDcardHide', function(name) {
	return name.replace(/(\d{8})\d{8}(\d*)/, '$1********$2')
});
// 人气数字转换
Vue.filter('digitalConversion', function(str) {
	let num = Math.abs(str);
	if (String(num).length < 5) {
		return num;
	} else {
		return (num / 10000).toFixed(1) + 'W';
	}
})
// timeAgo
Vue.filter('timeAgo', function(time) {
	time = String(time).length <= 10 ? time * 1000 : time;
	var arr = [
			[],
			[]
		],
		stamp = new Date().getTime() - new Date(time).getTime();
	//返回具体日期
	if (stamp > 1000 * 60 * 60 * 24 * 8) {
		stamp = new Date(time);
		arr[0][0] = digit(stamp.getFullYear(), 4);
		arr[0][1] = digit(stamp.getMonth() + 1);
		arr[0][2] = digit(stamp.getDate());
		return arr[0].join('-') + ' ' + arr[1].join(':');
	}
	//30天以内，返回“多久前”
	if (stamp >= 1000 * 60 * 60 * 24) {
		return ((stamp / 1000 / 60 / 60 / 24) | 0) + '天前';
	} else if (stamp >= 1000 * 60 * 60) {
		return ((stamp / 1000 / 60 / 60) | 0) + '小时前';
	} else if (stamp >= 1000 * 60 * 2) { //2分钟以内为：刚刚
		return ((stamp / 1000 / 60) | 0) + '分钟前';
	} else {
		return '刚刚';
	}
})
//Vue数字过滤器逢三一断
Vue.filter('NumFormat', function(value) {
	if (!value) return '0.00';
	/*原来用的是Number(value).toFixed(0)，这样取整时有问题，例如0.51取整之后为1，感谢Nils指正*/
	/*后来改成了 Number(value)|0,但是输入超过十一位就为负数了，具体见评论 */
	var intPart = Number(value) - Number(value) % 1; //获取整数部分（这里是windy93的方法）
	var intPartFormat = intPart.toString().replace(/(\d)(?=(?:\d{3})+$)/g, '$1,'); //将整数部分逢三一断
	var floatPart = ".00"; //预定义小数部分
	var value2Array = value.toString().split(".");
	//=2表示数据有小数位
	if (value2Array.length == 2) {
		floatPart = value2Array[1].toString(); //拿到小数部分
		if (floatPart.length == 1) { //补0,实际上用不着
			return intPartFormat + "." + floatPart + '0';
		} else {
			return intPartFormat + "." + floatPart;
		}
	} else {
		return intPartFormat + floatPart;
	}
})
//数字前置补零
function digit(num, length) {
	var str = '';
	num = String(num);
	length = length || 2;
	for (var i = num.length; i < length; i++) {
		str += '0';
	}
	return num < Math.pow(10, length) ? str + (num | 0) : num;
}
//null转空字符串
Vue.filter('FilterNullToEmpty', function(obj, propertyName) {
	if (obj) {
		return obj[propertyName];
	}
	return '';
});
//金额格式化显示
Vue.filter('FilterAmountFormat', function(number) {
	if (number) {
		number = Math.round(parseFloat(number) * 100) / 100; //保留两位小数
		let numStrings = number.toString().split('.');
		let integerFraction = numStrings[0];
		let decimalFraction = '00';
		if (numStrings.length > 1) {
			decimalFraction = numStrings[1] == null ? '00' : numStrings[1].padEnd(2, '0');
		}
		return `${integerFraction}.${decimalFraction}`;
	}
	return '0.00';
});
//数字格式化显示
Vue.filter('FilterMoneyFormat', function(num, unit) {
	if (unit) unit = '(' + unit + ')';
	else unit = '';
	if (num) {
		num = Math.round(parseFloat(num) * 100) / 100; //保留两位小数
		let numStrings = num.toString().split('.');
		let integerFraction = numStrings[0];
		let decimalFraction = '00';
		if (numStrings.length > 1) {
			decimalFraction = numStrings[1] == null ? '00' : numStrings[1].padEnd(2, '0');
		}
		return `${integerFraction}.${decimalFraction}` + unit;
	}
	return '0.00' + unit;
});
//字符串过长截断
Vue.filter('FilterTextMaxLength', function(content, maxLen) {
	if (content) {
		let len = content.length;
		if (!maxLen) {
			maxLen = 10;
		}
		if (len > maxLen) {
			return content.substring(0, maxLen) + '...';
		}
	}
	return content;
});
//数字格式化显示,单位为万
Vue.filter('FilterWanFormat', function(num, unit) {
	if (num) {
		num = num.toFixed(2);
		num = parseFloat(num) / 10000;
		num = num.toLocaleString();
		if (unit) unit = '(' + unit + ')';
		else unit = '';
		return num + unit; //返回的是字符串23,245.12保留2位小数
	} else return num;
});
//身份证隐藏
Vue.filter('FilterIdCard', function(code) {
	if (code) {
		let newCode = '';
		if (code.length == 18) newCode = code.substring(0, 10) + "***" + code.substring(16, 18);
		else if (code.length == 15) newCode = code.substring(0, 8) + "***" + code.substring(13, 15);
		return newCode;
	} else return code;
});

function oninput(val, limit = 0) {
	val = val.replace(/[^\d.]/g, ""); //保留数字
	val = val.replace(/^00/, "0."); //开头不能有两个0
	val = val.replace(/^\./g, "0."); //开头为小数点转换为0.
	val = val.replace(/\.{2,}/g, "."); //两个以上的小数点转换成一个
	val = val.replace(".", "$#$").replace(/\./g, "").replace("$#$", "."); //只保留一个小数点
	/^0\d+/.test(val) ? val = val.slice(1) : ''; //两位以上数字开头不能为0
	const str = '^(\\d+)\\.(\\d{' + limit + '}).*$'
	const reg = new RegExp(str)
	if (limit === 0) {
		// 不需要小数点
		val = val.replace(reg, '$1')
	} else {
		// 通过正则保留小数点后指定的位数
		val = val.replace(reg, '$1.$2')
	}
	return val
}